package com.li.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.li.domain.Menu;
import com.li.service.MenuService;
import com.li.utlis.MenuUtil;
import com.li.utlis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @RequestMapping("/listMenu")
    public List<Menu> listMenu(){
        return menuService.list();
    }

    @RequestMapping("/listMenuTree")
    public List<Menu> listMenuTree(Menu menu){
        return MenuUtil.recursion(menuService.list(new QueryWrapper<Menu>().orderByAsc("order_num")));
    }

    @RequestMapping("/listQueryMenuTree")
    public List<Menu> listQueryMenuTree(Menu menu){
        List<Menu> list=menuService.listQueryMenuTree(menu);
        return MenuUtil.recursion(list);
    }

    @PostMapping("/saveOrUpdateMenu")
    public JSONObject saveOrUpdateMenu(Menu menu){
        try {
            if (menu.getMenuId()==null){
                menuService.addMenu(menu);
            }else {
                menuService.updateMenu(menu);
            }
        }catch (Exception e){
            return R.getError(menu);
        }
        return R.getSuccess();
    }

    @RequestMapping("/editMenu/{menuId}")
    public Menu editMenu(@PathVariable("menuId") Integer menuId){
        return menuService.getById(menuId);
    }

    @GetMapping("/delMenu/{menuId}")
    public JSONObject delMenu(@PathVariable("menuId") Integer menuId){
        boolean flag = menuService.delMenu(menuId);
        if (flag){
            return R.getSuccess();
        }else {
            return R.getError(menuId);
        }
    }

}
